package com.sdy.healthcode.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.healthcode.biz.constants.Constants;
import com.sdy.healthcode.biz.dto.Address;
import com.sdy.healthcode.biz.dto.PersonInfoVo;
import com.sdy.healthcode.biz.dto.ThisCourtVO;
import com.sdy.healthcode.biz.model.HsDepartment;
import com.sdy.healthcode.biz.param.PersonnelIdParam;
import com.sdy.healthcode.biz.param.UpdatePersonnelParam;
import com.sdy.healthcode.biz.service.HsDepartmentService;
import com.sdy.healthcode.biz.service.UserService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.sdy.common.model.Response;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.healthcode.web.controller
 * @date:2020/3/1
 */

@Slf4j
@RestController
@RequestMapping("/thisCourt")
@Api(tags = "本院人员管理")
public class ThisCourtController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private HsDepartmentService hsDepartmentService;

    private void checkManager(HttpServletRequest request) throws BizException {
        Assert.isNull(getUserId(request, Constants.SESSION_WEB_USER_ID), "权限不足");
    }

    @GetMapping("/getPage")
    @ApiOperation(value = "本院人员分页")
    public Response getPage(HttpServletRequest request, String name, Integer type, Page<ThisCourtVO> page) throws UnsupportedEncodingException {
        if (StringUtil.isNotBlank(name)) {
            name = URLDecoder.decode(name, StandardCharsets.UTF_8.name());
        }
        List<ThisCourtVO> page1 = userService.getPage(name, type, page);
        for (ThisCourtVO thisCourtVO : page1) {
            Address addr = Address.fromStrToSingleAddr(thisCourtVO.getAddr());
            thisCourtVO.setAddr(addr == null ? "" : addr.getArea() + " " + addr.getAddr());
        }
        Integer pageSize = userService.getPageSize(name, type);
        return Response.success(new Page<ThisCourtVO>(page.getCurrent(), page.getSize(), pageSize).setRecords(page1));
    }

    @PostMapping("/updAuthScan")
    @ApiOperation(value = "启用/取消 扫码权限")
    public Response updAuthScan(HttpServletRequest request, Integer id, Integer type) throws BizException {
        checkManager(request);
        userService.updAuthScan(id, type);
        return Response.success();
    }

    @ApiOperation(value = "查询人员信息列表", response = PersonInfoVo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "state", value = "状态 0-禁用 1-启用 "),
            @ApiImplicitParam(name = "type", value = "是否为本院人员 0-否 1-是"),
            @ApiImplicitParam(name = "nameOrPhone", value = "姓名或者手机号模糊查询"),
            @ApiImplicitParam(name = "deptName", value = "科室模糊查询"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/getPersonPageList")
    public Response getPersonPageList(Integer state, Integer type, String nameOrPhone, String deptName, Integer current, Integer size) throws BizException, UnsupportedEncodingException {
        if (StringUtil.isNotBlank(nameOrPhone)) {
            nameOrPhone = URLDecoder.decode(nameOrPhone, StandardCharsets.UTF_8.name());
        }
        if (StringUtil.isNotBlank(deptName)) {
            deptName = URLDecoder.decode(deptName, StandardCharsets.UTF_8.name());
        }
        IPage<PersonInfoVo> personPageList = userService.getPersonPageList(state, type, nameOrPhone, deptName, current, size);
        // 去@@处理
        List<PersonInfoVo> records = personPageList.getRecords();
        for (PersonInfoVo record : records) {
            Address addr = Address.fromStrToSingleAddr(record.getAddr());
            record.setAddr(addr == null ? "" : addr.getArea() + " " + addr.getAddr());
        }
        IPage<PersonInfoVo> personInfoVoIPage = personPageList.setRecords(records);
        return Response.success(personInfoVoIPage);
    }


    @ApiOperation(value = "修改人员信息")
    @PostMapping("/updatePersonnel")
    public Response updatePersonnel(@ApiParam(name = "param", value = "修改人员基本信息参数类") @RequestBody UpdatePersonnelParam param) throws BizException {
        userService.updatePersonnel(param);
        return Response.success();
    }

    @ApiOperation(value = "删除人员信息")
    @PostMapping("/delPersonnel")
    public Response delPersonnel(@ApiParam(name = "param", value = "删除人员信息参数") @RequestBody PersonnelIdParam param) throws BizException {
        userService.delPersonnel(param);
        return Response.success();
    }

    @ApiOperation(value = "禁用账户/启用账户")
    @PostMapping("/disablePerson")
    public Response disablePerson(@ApiParam(name = "param", value = "禁用/启用账户参数") @RequestBody PersonnelIdParam param) throws BizException {
        userService.disablePerson(param);
        return Response.success();
    }


    @ApiOperation(value = "给用户授权/给用户取消授权")
    @PostMapping("/powerPerson")
    public Response powerPerson(@ApiParam(name = "param", value = "给用户授权/取消授权参数") @RequestBody PersonnelIdParam param) throws BizException {
        userService.powerPerson(param);
        return Response.success();
    }

    @GetMapping("/hsDepartmentData")
    @ApiOperation(value = "医院部门数据")
    public Response hsDepartmentData() {
        List<HsDepartment> depts = hsDepartmentService.list();
        return Response.success(depts.stream().map(d -> {
            HashMap<Object, Object> m = new HashMap<>();
            m.put("name", d.getName());
            m.put("value", d.getId() + "");
            m.put("parent", d.getParentId() > 0 ? d.getParentId() + "" : 0);
            return m;
        }).collect(Collectors.toList()));
    }

    @GetMapping("/departmentDataClassification")
    @ApiOperation(value = "医院部门数据根据首字母分类")
    public Response departmentDataClassification() {
        List<HsDepartment> depts = hsDepartmentService.list();
//        Collator instance = Collator.getInstance(Locale.CHINA);
//        Collections.sort(depts.stream().map(HsDepartment::getName).collect(Collectors.toList()), instance);
        Map<String, Object> deptMap = new HashMap<>(16);
        for (int i = 1; i <= 26; i++) {
            String word = String.valueOf((char) (96 + i)).toUpperCase();
            List<HsDepartment> letter = new ArrayList<>();
            for (HsDepartment one : depts) {
                String name = one.getName();
                String firstWord = "";
                if (StringUtil.isNotBlank(name)) {
                    firstWord = getFirstWord(name);
                    if (word.equals(firstWord)) {
                        letter.add(one);
                    }
                }
            }
            deptMap.put(word, letter);
        }
        return Response.success(deptMap);
    }

    private String getFirstWord(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return (convert.substring(0, 1).toUpperCase());
    }

}
